/**
 # # THIS FILE IS PART OF ripap PROJECT
 # #
 # MyBeanSerializerModifier.java - MyBeanSerializerModifier
 # 
 # THIS PROGRAM IS OPENSOURCE SOFTWARE, IS LICENSED UNDER BSD
 # YOU SHOULD HAVE RECEIVED A COPY OF WTFPL LICENSE
 # 
 # Copyright (c) 2018 Ting Fan
 */
package com.cloudkinto.config.json;


import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MyBeanSerializerModifier extends BeanSerializerModifier {

    //  数组类型
    private JsonSerializer _nullArrayJsonSerializer = new MyNullArrayJsonSerializer();
    // 字符串等类型
    private JsonSerializer _nullJsonSerializer = new MyNullJsonSerializer();

    //  map类型
    private JsonSerializer _nullMapJsonSerializer = new MyNullMapSerializer();

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                                     List beanProperties) {
        //循环所有的beanPropertyWriter
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
            //判断字段的类型，如果是array，list，set则注册nullSerializer
            if (isArrayType(writer)) {
                if(isMapType(writer)){
                    writer.assignNullSerializer(this._nullMapJsonSerializer);
                }else{
                    //给writer注册一个自己的nullSerializer
                    writer.assignNullSerializer(this._nullArrayJsonSerializer);
                }

            } else {
                writer.assignNullSerializer(this._nullJsonSerializer);
            }
        }
        return beanProperties;
    }

    //判断是什么类型
    protected boolean isArrayType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class)|| clazz.equals(Collection.class) || clazz.equals(Map.class) ;
    }

    protected boolean isMapType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.equals(Map.class);
    }

}